package com.dawn.modules.chat.controller;

import com.dawn.modules.chat.tools.NoteTools;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import com.dawn.modules.chat.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import com.dawn.modules.chat.dto.ChatRequest;


@Tag(name = "TeacherController", description = "教师智能体接口")
@RestController
@RequestMapping("/api/chat")
public class ChatController {
    //private final OpenAiChatModel model;
    private static final Logger debugLogger = LoggerFactory.getLogger(ChatController.class);
    @Autowired
    private ChatService chatService;
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private NoteTools noteTools;
    // 系统提示词
    @Value("classpath:teacher-prompt-template.txt")
    private Resource systemPrompt;
    // 构造函数注入
    //public ChatController(OpenAiChatModel model) {
    //    this.model = model;
    //}
    /**
     * 新建普通对话
     */
    @Operation(summary = "教师智能体chat接口")
    @PostMapping("/newMessage")
    public String chat(@RequestBody ChatRequest chatRequest) {
        String grade = chatRequest.getGrade();
        String course = chatRequest.getSubject();
        String pattern = chatRequest.getMode();
        String message = chatRequest.getUserInputContent();
        // 提示词按照用户需求进行转换。
        String parsePromptText = chatService.parsePromptText(grade, course, pattern);
        // 提示词和用户输入问题拼接。
        Prompt prompt = new Prompt(parsePromptText);


        debugLogger.info(prompt.toString());
        // 调用模型
        //Flux<String> content = chatClient.prompt(prompt).user(message).stream().content();
        ChatResponse chatResponse = chatClient
                .prompt(prompt)
                .system(systemPrompt)
                .user(message)
                .tools(noteTools)
                .call()
                .chatResponse();
        String text = null;
        if (chatResponse != null) {
            text = chatResponse.getResult().getOutput().getText();
        }
        System.out.println(text);
        // 返回
        return text;
    }
}